package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.LoginDto;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApUserLoginServiceImpl implements ApUserLoginService {

    @Autowired
    ApUserMapper apUserMapper;

    /**
     * app端登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        //参数校验
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //账号密码任意为空的同时,设备登录状态也为空,不能够放行
        if((StringUtils.isBlank(dto.getPhone())||StringUtils.isBlank(dto.getPassword())
                &&StringUtils.isBlank(dto.getEquipmentId().toString()))){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"请使用账号密码或者游客登录");
        }

        if(StringUtils.isNotBlank(dto.getPhone())||StringUtils.isNotBlank(dto.getPassword())){
            //使用了账号密码登录
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery()
                    .eq(ApUser::getPhone, dto.getPhone())
                    .eq(ApUser::getStatus, 0));
            if (apUser==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"账号不存在或者已经被封停");
            }
            String newPassword = DigestUtils.md5DigestAsHex((dto.getPassword() + apUser.getSalt()).getBytes());
            if(!apUser.getPassword().equals(newPassword)){
                return ResponseResult.errorResult(AppHttpCodeEnum.NUMBER_DOTEXIT_OR_CLOSURE);
            }
            String token = AppJwtUtil.getToken(apUser.getId().longValue());
            HashMap<Object, Object> map = new HashMap<>();
            map.put("token",token);
            apUser.setSalt(null);
            apUser.setPassword(null);
            map.put("user",apUser);
            //5.返回结果封装回前端
            return ResponseResult.okResult(map);
        }else{
            Map<String,Object> map = new HashMap<>();
            map.put("token",AppJwtUtil.getToken(0l));
            return ResponseResult.okResult(map);
        }
    }
}